#include "CustomConvertor.h"

#include <LDM/converters/SoConverterParameters.h>

#include <VolumeViz/readers/SoVRSegyFileReader.h>
#include <VolumeViz/converters/SoVolumeConverter.h>

class CustomConvertor::CustomConvertorPrivate : public QObject, public SoVolumeConverter
{
  Q_OBJECT;

public:

  CustomConvertorPrivate( CustomConvertor* self )
    : m_self( self ),
      m_parameters( new SoConverterParameters ),
      m_theSegYReader( 0 ) {
  }

  ~CustomConvertorPrivate() {
    if( m_theSegYReader != NULL ) {
      m_theSegYReader->unrefNoDelete();
    }
    if( m_parameters != NULL ) {
      delete m_parameters;
    }
  }

  void convert() {
    SoVolumeConverter::convert( m_parameters );
  }

  virtual void startConversion() {
  }

  virtual Abort progress( int numTilesGenerated, int numTilesToGenerate ) {
    emit progressChanged( float(numTilesGenerated)/numTilesToGenerate*100 );
    return SoVolumeConverter::progress( numTilesGenerated, numTilesToGenerate );
  }

  virtual void endConversion() {
  }

  void setReader( SoVRSegyFileReader* reader) {
    if( m_theSegYReader != NULL ) {
      m_theSegYReader->unrefNoDelete();
    }

    m_theSegYReader = reader;
    m_theSegYReader->ref();
  }

  virtual SoVolumeReader* getReader( const SbString& filename, const SbString& fileExt ) {
    return m_theSegYReader;
  }

signals:

  void progressChanged( int );

public:

  CustomConvertor*         m_self;
  SoConverterParameters*   m_parameters;
  SoVRSegyFileReader*      m_theSegYReader;
};

CustomConvertor::CustomConvertor()
  : _privateData( new CustomConvertorPrivate( this ) )
{
  connect( _privateData, SIGNAL( progressChanged( int ) ), this, SIGNAL( progressChanged( int ) ) );
}

CustomConvertor::~CustomConvertor()
{
  delete _privateData;
}

int CustomConvertor::convert( SoConverterParameters* parameters )
{
  memcpy( _privateData->m_parameters, parameters, sizeof(SoConverterParameters) );

  start();

  return SoVolumeConverter::CVT_NO_ERROR;
}

void CustomConvertor::run()
{
  _privateData->convert();
}

#include "CustomConvertor.moc"